import {h} from 'vue'
import {ElNotification} from 'element-plus'
import {
  RouteRecordRaw,
  RouteComponent,
  NavigationFailureType,
  isNavigationFailure
} from 'vue-router'
import {getTreeInfor, getTreeInforByList, traveTree} from '@/util/common'
import {Dictionary} from '@/api/config'
import useNav, {WelcomeView, MenuView, MenuType} from '@/store/nav'
import router from '@/router/index'
import mitt from '@/util/mitt'
import {getUserInfoByUser} from '@/api/login'
import {getInstitutionalData} from '@/api/baseSetting/institutionalData'
import useUser from '@/store/user'
import {homeRoute, HOMENAME} from '@/router/static'
import {showMessageBox} from '@/util/element'
const user = useUser.setup().store
const nav = useNav.setup().store

//基础静态菜单 TODO 有角色权限后不导出
export const MenusStatic: Array<MenuView> = [
  // {
  //   label: '公共健康体检',
  //   code: 'PublicHealthExamination',
  //   path: '/publicHealthExamination',
  //   icon: 'sidebar-public-health-examination',
  //   menuType: MenuType.CATALOG,
  //   children: [
  //     {
  //       label: '体检登记',
  //       code: 'PhysicalExaminationRegister',
  //       path: '/publicHealthExamination/physicalExaminationRegister',
  //       menuType: MenuType.MENU
  //     },
  //     {
  //       label: '社区设置',
  //       code: 'CommunitySettings',
  //       path: '/publicHealthExamination/communitySettings',
  //       menuType: MenuType.MENU
  //     },
  //     {
  //       label: '档案管理',
  //       code: 'ResidentArchives',
  //       path: '/publicHealthExamination/residentArchives',
  //       menuType: MenuType.MENU
  //     }
  //   ]
  // },
  // {
  //   label: '医生诊台',
  //   code: 'MedicalExaminerDesk',
  //   path: '/medicalExaminerDesk',
  //   icon: 'sidebar-medical-examiner-desk',
  //   menuType: MenuType.CATALOG,
  //   children: [
  //     {
  //       label: '医生诊台',
  //       code: 'MedicalExaminerDesk',
  //       path: '/medicalExaminerDesk',
  //       menuType: MenuType.MENU
  //     }
  //   ]
  // },
  // {
  //   label:'体检报告',
  //   code:'ReportCatalog',
  //   path:'/report',
  //   icon:'sidebar-physical-report',
  //   menuType:MenuType.CATALOG,
  //   children:[
  //     {
  //       label:'体检报告',
  //       code:'PhysicalReport',
  //       path:'/report/physicalReport',
  //       menuType:MenuType.MENU
  //     }
  //   ]
  // },
  // {
  //   label: '统计分析',
  //   code: 'StatisticalAnalysis',
  //   path: '/statisticalAnalysis',
  //   menuType: MenuType.CATALOG,
  //   icon: 'sidebar-statistical-analysis',
  //   children: [
  //     {
  //       label: '体检明细统计',
  //       code: 'PhyDetailedStatistics',
  //       path: '/statisticalAnalysis/phyDetailedStatistics',
  //       menuType: MenuType.MENU
  //     },
  //     {
  //       label: '异常结果统计',
  //       code: 'AbnormalResultStatistics',
  //       path: '/statisticalAnalysis/abnormalResultStatistics',
  //       menuType: MenuType.MENU
  //     },
  //     {
  //       label: '体检工作量统计',
  //       code: 'WorkloadStatistics',
  //       path: '/statisticalAnalysis/workloadStatistics',
  //       menuType: MenuType.MENU
  //     }
  //   ]
  // },
  // {
  //   label: '数据管理',
  //   code: 'DataManagement',
  //   path: '/dataManagement',
  //   icon: 'sidebar-data-management',
  //   menuType: MenuType.CATALOG,
  //   children: [
  //     {
  //       label: '上传公卫平台',
  //       code: 'UploadPublicHealthPlatform',
  //       path: '/dataManagement/uploadPublicHealthPlatform',
  //       menuType: MenuType.MENU
  //     },
  //     {
  //       label: '数据上传',
  //       code: 'DataUpload',
  //       path: '/dataManagement/dataUpload',
  //       menuType: MenuType.MENU
  //     }
  //   ]
  // },
  // {
  //   label: '检验信息',
  //   code: 'ExaminationManager',
  //   path: '/examinationManager',
  //   icon: 'sidebar-physical-examination-manager',
  //   menuType: MenuType.CATALOG,
  //   children: [
  //     {
  //       label: '标本采录',
  //       code: 'Specimen',
  //       path: '/examinationManager/specimen',
  //       menuType: MenuType.MENU
  //     },
  //     {
  //       label: '检验结果审核',
  //       code: 'ResultReview',
  //       path: '/examinationManager/resultReview',
  //       menuType: MenuType.MENU
  //     }
  //   ]
  // },
  // {
  //   label: '体检管理',
  //   code: 'PhysicalExaminationManager',
  //   path: '/physicalExaminationManager',
  //   icon: 'sidebar-physical-examination-manager',
  //   menuType: MenuType.CATALOG,
  //   children: [
  //     {
  //       label: '体检科室',
  //       code: 'Department',
  //       path: '/physicalExaminationManager/department',
  //       menuType: MenuType.MENU
  //     },
  //     {
  //       label: '体检大类',
  //       code: 'MajorCategories',
  //       path: '/physicalExaminationManager/majorCategories',
  //       menuType: MenuType.MENU
  //     },
  //     {
  //       label: '体检项目',
  //       code: 'PhysicalItems',
  //       path: '/physicalExaminationManager/physicalItems',
  //       menuType: MenuType.MENU
  //     },
  //     {
  //       label: '项目组合',
  //       code: 'ProjectPortfolio',
  //       path: '/physicalExaminationManager/projectPortfolio',
  //       menuType: MenuType.MENU
  //     },
  //     {
  //       label: '健教指导',
  //       code: 'HealthGuide',
  //       path: '/physicalExaminationManager/healthGuide',
  //       menuType: MenuType.MENU
  //     },
  //     {
  //       label: '体检套餐',
  //       code: 'PhysicalPackage',
  //       path: '/physicalExaminationManager/physicalPackage',
  //       menuType: MenuType.MENU
  //     },
  //     {
  //       label: '体检知识库',
  //       code: 'PhysicalKnowlege',
  //       path: '/physicalExaminationManager/physicalKnowlege',
  //       menuType: MenuType.MENU
  //     }
  //   ]
  // },
  // {
  //   label: '仪器设备',
  //   code: 'Instrument',
  //   path: '/instrument',
  //   menuType: MenuType.CATALOG,
  //   icon: 'sidebar-Instrument-and-equipment',
  //   children: [
  //     {
  //       label: '检验设备',
  //       code: 'Inspection',
  //       path: '/instrument/inspection',
  //       menuType: MenuType.MENU
  //     },
  //     {
  //       label: '检查设备',
  //       code: 'Examine',
  //       path: '/instrument/examine',
  //       menuType: MenuType.MENU
  //     }
  //   ]
  // },
  {
    label: '书籍管理',
    code: 'BaseSetting',
    path: '/baseSetting',
    menuType: MenuType.CATALOG,
    icon: 'sidebar-base-setting',
    children: [
      // {
      //   label: '机构资料',
      //   code: 'InstitutionalData',
      //   path: '/baseSetting/institutionalData',
      //   menuType: MenuType.MENU
      // },
      {
        label: '账号管理',
        code: 'AccountManager',
        path: '/baseSetting/accountManager',
        menuType: MenuType.MENU
      },
      {
        label: '书籍管理',
        code: 'RoleManager',
        path: '/baseSetting/labSign',
        menuType: MenuType.MENU
      },
      // {
      //   label: '书籍管理',
      //   code: 'BookManager',
      //   path: '/baseSetting/roleManager',
      //   menuType: MenuType.MENU
      // },
      {
        label: '书籍类型',
        code: 'DictionaryManager',
        path: '/baseSetting/dictionaryManager',
        menuType: MenuType.MENU
      }
      // {
      //   label: '系统日志',
      //   code: 'SystemLog',
      //   path: '/baseSetting/systemLog',
      //   menuType: MenuType.MENU
      // }
    ]
  }
]

//不在菜单配置的页面
const MenusNoRequire: Array<MenuView> = [
  {
    label: '个人中心',
    code: 'Personal',
    path: '/personal',
    hide: true
  },
  {
    label: '维护检验项目',
    code: 'MaintenanceItem',
    path: '/instrument/inspection/maintenanceItem',
    query:{id:true},
    hide: true
  },
  {
    label: '维护参考区间',
    code: 'ReferenceRange',
    path: '/instrument/inspection/referenceRange',
    query:{id:true},
    hide: true
  },
  {
    label: '维护检查项目',
    code: 'MaintenanceChecks',
    path: '/instrument/examine/maintenanceChecks',
    query:{id:true},
    hide: true
  },
  {
    label: '开始体检',
    code: 'BeginPhysicalExamination',
    path: '/medicalExaminerDesk/beginPhysicalExamination',
    query:{id:true},
    hide: true
  },
  {
    label: '中医体质辨识',
    code: 'ConstitutionIdentify',
    path: '/medicalExaminerDesk/constitutionIdentify',
    query:{id:true},
    hide: true
  },
  {
    label: '体检知识库配置',
    code: 'ManagePhysicalKnowlege',
    path: '/physicalExaminationManager/physicalKnowlege/manage',
    query:{id:true},
    hide: true
    // component:() => import('@/views/pages/physicalExaminationManager/physicalKnowlege/manageKnowlege.vue')
  }
]

//在菜单配置的页面 require必填 依赖菜单的编码
const MenusRequire: Array<MenuView> = []

//后端数据转换
export const getMenuView = (data: Array<MenuView>): Array<MenuView> => {
  return data
}

const modules: Dictionary<RouteComponent> = import.meta.glob(
  '/src/views/pages/**/index.vue'
)
//设置路由的组件
const setRouterComponent = (
  menuView: MenuView,
  router: RouteRecordRaw
): boolean => {
  router.path = '/home' + menuView.path
  const module = modules['/src/views/pages' + menuView.path + '/index.vue']
  if (menuView.component) router.component = menuView.component
  else router.component = module ? module : {render: () => h('div')}
  return true
}

//菜单数据转换成路由数据
export const getRouteView = (data: Array<MenuView>): Array<RouteRecordRaw> => {
  const props = {path: 'path', name: 'code'}
  //扁平化路由
  const routers = getTreeInforByList<MenuView, RouteRecordRaw>(
    data,
    props,
    false,
    setRouterComponent
  )
  return routers
}

//用户路由
export const initRoutes = (_menus: Array<MenuView>) => {
  return new Promise<Array<RouteRecordRaw>>((resolve, reject) => {
    if (!_menus || _menus.length === 0) reject()
    //欢迎界面
    let menus: Array<MenuView> = _menus.concat(WelcomeView)
    //隐藏的界面
    menus = menus.concat(MenusNoRequire).concat(MenusRequire)
    const closeTab = MenusNoRequire.map((item) => {
      return item.code
    })
    useNav.setup().init(menus, closeTab)
    const routers = getRouteView(menus)
    resolve(routers)
  })
}

export enum RouterPushType {
  Sider,
  Tab,
  Others
}

//路由跳转
export const routerPush = (
  menu: MenuView | string | null,
  query?: any,
  source?: RouterPushType
) => {
  if (!menu) return false
  const nav = useNav.setup().store
  const menuView: MenuView | null =
    typeof menu === 'string' ? nav.getNavTabByCode(menu) : menu
  if (!menuView) return
  nav.setNavSeleteTab(menuView.code)
  router
    .push({name: menuView.code, query})
    .then((failure) => {
      if (isNavigationFailure(failure, NavigationFailureType.aborted)) {
        ElNotification.error('路由跳转被中止')
      } else if (
        isNavigationFailure(failure, NavigationFailureType.cancelled)
      ) {
        ElNotification.error('路由跳转被取消')
      } else if (
        isNavigationFailure(failure, NavigationFailureType.duplicated)
      ) {
        mitt.emit('routerDuplicated', source)
      }
      nav.navLoading = false
    })
    .catch((error) => {
      ElNotification.error('路由跳转错误' + error)
      nav.navLoading = false
    })
}

/**
 * @description: 根据code过滤重新生成路由树
 * @param {Array} leafMenuData //左侧菜单叶子节点code数据
 * @return {*}
 */
export const restoreTree = (leafMenuData: Array<string>): Array<MenuView> => {
  //标记关系
  const relationMap: Dictionary<{
    code: string
    childrenNum: number
    parentCode: string
    delete: boolean
  }> = {}
  const setRelationMap = (data: MenuView) => {
    const childrenNum = data.children ? data.children.length : 0
    if (!relationMap[data.code])
      relationMap[data.code] = {
        code: data.code,
        childrenNum,
        parentCode: '',
        delete: true
      }
    else relationMap[data.code].childrenNum = childrenNum
    if (data.children && data.children.length) {
      data.children.forEach((item) => {
        if (!relationMap[item.code])
          relationMap[item.code] = {
            code: item.code,
            parentCode: data.code,
            childrenNum: 0,
            delete: true
          }
      })
    }
  }
  traveTree(MenusStatic, setRelationMap)
  //标记是否删除
  leafMenuData.forEach((code) => {
    let currentCode = code
    while (currentCode) {
      const relationData = relationMap[currentCode]
      if (relationData) {
        currentCode = relationData.parentCode
        relationData.delete = false
      } else {
        currentCode = ''
      }
    }
  })
  const props = {
    code: 'code',
    label: 'label',
    path: 'path',
    icon: 'icon',
    menuType: 'menuType'
  }
  const filter = (oldNode: MenuView) => {
    const relationData = relationMap[oldNode.code]
    return relationData.delete
  }
  return getTreeInfor<MenuView, MenuView>(MenusStatic, props, filter)
}

/**
 * @description: 根据权限动态设置路由
 * @return {*}
 */
export const getRoutesByAuth = () => {
  initRoutes(MenusStatic).then((routers) => {
    homeRoute.children = routers
    if (router.hasRoute(HOMENAME)) router.removeRoute(HOMENAME)
    router.addRoute(homeRoute)
    if (nav.navJumpMenu) {
      routerPush(nav.navJumpMenu.code, nav.navJumpMenu.query)
      nav.navJumpMenu = null
    } else {
      routerPush(nav.navTabSelete)
    }
  })
  // //获取用户基本信息
  // getUserInfoByUser()
  //   .then((res) => {
  //     const {data} = res.data
  //     user.refreshUserInfo(data)
  //     const leafMenuData: Array<string> = data.menuJson ? JSON.parse(data.menuJson) : []
  //     return initRoutes(restoreTree(leafMenuData))
  //   })
  //   .then((routers) => {
  //     homeRoute.children = routers
  //     if (router.hasRoute(HOMENAME)) router.removeRoute(HOMENAME)
  //     router.addRoute(homeRoute)
  //     if (nav.navJumpMenu) {
  //       routerPush(nav.navJumpMenu.code, nav.navJumpMenu.query)
  //       nav.navJumpMenu = null
  //     } else {
  //       routerPush(nav.navTabSelete)
  //     }
  //   })
  //   .catch((error) => {
  //     showMessageBox('获取菜单失败或未配置菜单', {
  //       title: '错误信息',
  //       confirmText: '重新登录',
  //       cancelText:'知道了',
  //       secondMessage: error + '\n请刷新页面或重新登录',
  //       mesageType: 'second'
  //     }).then(() => {
  //       router.push({name:'Login'})
  //     })
  //   })
  //获取用户机构信息
  // getInstitutionalData().then((res) => {
  //   const {data} = res.data
  //   user.refreshUserOrgInfo(data)
  // })
}
